#pragma once
#include <d3d9.h>
#include <d3dx9.h>
#include "../utility/defs.h"
#include "../utility/Gets.h"
#include "../utility/simpleds.h"
#include "../utility/light.h"
#include "../utility/vertex.h"
#include "../shaderMgr.h"
#include "../textureMgr.h"
#include <vector>
#include <string>
using namespace std;

const int DefaultRows = 17;
const int DefaultCols = 17;
const float DefaultDD = 150.0f;
const float DefaultDW = 150.0f;
const float DefaultWidth = DefaultDW*(DefaultCols-1);
const float DefaultDepth = DefaultDD*(DefaultRows-1);
const D3DXVECTOR3 DefaultCenter = D3DXVECTOR3(0.0f,0.0f,0.0f);

const float EPSILON = 0.001f;

const string gTex[] = {"gTex0","gTex1","gTex2","gTex3"};
void GenerateGridPos(int rows,int cols,float width,float depth,D3DXVECTOR3 center,
	vector<D3DXVECTOR3>& vecPos);

enum LODLEVEL{
	LODL1,
	LODL2,
};

class cTerrainBase
{
public:
	cTerrainBase();
	cTerrainBase(int rows,int cols,float width,float depth,D3DXVECTOR3 center);
	void CreateGrid(int rows,int cols,float width,float depth,
		D3DXVECTOR3 center,vector<D3DXVECTOR3>& vecPos);
	void CreateGridFromVertex(int rows,int cols,float width,float depth,
		D3DXVECTOR3 center,TerrainVertex* pVertex);
	void GenerateIndex();
	void SetSubGrid(int rID,int cID,int rows,int cols){
		m_rID = rID;
		m_cID = cID;
		m_parentRow = rows;
		m_parentCol = cols;
	}
	void SetLodLevel(int lodLevel){ 
		m_iLodLevel = lodLevel; 
		SetIndex();
	}
	void SetIndex();
	void SetDrawState(bool bDraw);

	ID3DXMesh* GetMesh(){ return m_pMesh; }

	void PushTexture(string strID);
	SPHERE& GetSphere(){ return m_sphere; }

	void Update(float dt);;
	void Render();
	void OnInit(string effectname);
	void Release();
private:
	void InitData(int rows,int cols,float width,float depth,D3DXVECTOR3 center);
	void SetBoundingSphere(TerrainVertex* pVertex);
	void SetIndexAndAttribute();
	void Optimize();
private:
	int m_rID,m_cID;
	int m_parentRow,m_parentCol;
	int m_iLodLevel;
	int m_iRows,m_iCols;
	int m_iFaceRows,m_iFaceCols;
	float m_fWidth,m_fDepth;
	float m_dd,m_dw;
	bool m_bDraw;
	SPHERE m_sphere;
	D3DXVECTOR3 m_vec3Center;
	vector<DWORD> vecLodL1Index;
	vector<DWORD> vecLodL2Index;

	LPDIRECT3DDEVICE9 m_pDevice9;
	ID3DXEffect* m_pEffect;
	ID3DXMesh* m_pMesh;
	vector<string> vecTexs;
	cShaderMgr* m_pShaderMgr;
	cTextureMgr* m_pTextureMgr;
};

